package com.nit.store.security.impl;

import com.nit.store.mapper.UserMapper;
import com.nit.store.pojo.vo.Permission;
import com.nit.store.pojo.vo.UserInfoDetails;
import com.nit.store.pojo.vo.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserLogin user = userMapper.getUserInfoByName(username);
        //判断用户是否存在
        if(user == null)
        {
            return null;
        }


        //判断用户是否被禁用
        if (user.getIsEnable()!=1){
            throw new DisabledException("账号被禁用！！请联系管理员！！！");
        }

        //授权
        List<Permission> permissions = user.getPermissions();
        //将授权数据转化为list类型
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(Permission permission:permissions){
            String permissionValue = permission.getValue();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
            authorities.add(authority);
        }

        //封装该类数据 转化成jwt
        UserInfoDetails userInfoDetails = new UserInfoDetails();
        userInfoDetails.setUid(user.getUid());
        userInfoDetails.setUsername(user.getUsername());
        userInfoDetails.setPassword(user.getPassword());
        userInfoDetails.setAuthorities(authorities);
        userInfoDetails.setAvatar(user.getAvatar());
        return userInfoDetails;
    }
}
